package com.sfx.concurrent.demo.线程基础.线程的创建;

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "c.DeadLock")
public class DeadLock {
    private static final Object A = new Object();
    private static final Object B = new Object();

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            synchronized (A) {
                log.debug("lockA");
                // 线程t1获取了A对象的锁, 1s 之后,又要获取B对象的锁
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (B) {
                    log.debug("lockB");
                    log.debug("操作...");
                }
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            synchronized (A) {  // 调整获取锁的顺序
                log.debug("lockA");
                // 线程t2获取了A对象的锁, 1s 之后,又要获取B对象的锁
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (B) {
                    log.debug("lockB");
                    log.debug("操作...");
                }
            }
        }, "t2");

        t1.start();
        t2.start();
    }
}
